odoo.define('er.dynamic', function (require) {
"use strict";

    var core = require('web.core');
    var form_common = require('web.form_common');
    var formats = require('web.formats');
    var Model = require('web.Model');
    var Widget = require('web.Widget');
    var FormView = require('web.FormView');
    var QWeb = core.qweb;

    var Comment = new Model('tyibs.er.work.order.comment');
    var SaveOrder = new Model('tyibs.er.work.order.save');
    var LiftModel = new Model("tyibs.base.lift");

    var work_order_sate = {
                    'draft': {'name':'尚未接警','icon':'fa fa-phone','icon_color':'bg-red'},
                    'center_received':{'name':'中心接警','icon':'fa-user','icon_color':'bg-yellow'},
                    "command_and_dispatch":{'name':"指挥调度",'icon':'fa fa-car','icon_color':'bg-blue'},
                    "keep_track_rescure":{'name':"救援跟踪",'icon':'fa fa-headphones','icon_color':'bg-green'},
                    "archive":{'name':"完成归档",'icon':'fa fa-archive','icon_color':'bg-gray'}
            };

    var work_order_sate_for_timeline = {
                    'draft': 1,
                    'center_received':2,
                    "command_and_dispatch":3,
                    "keep_track_rescure":4,
                    "archive":5
            };

    var SaveOrderListRowWidget = Widget.extend({
        template:"tyibs_er_save_order_list_row_template",
        init:function(parent, record){
            this._super(parent);
            this.record = record;
            var state = this.record['state'];
            this.state = state;
            this.record['state'] = work_order_sate[state]['name'];
            this.set_service_time();
        },
        set_service_time: function () {
            var self = this;
            self.service_time = new Date(self.record.service_time);
            self.service_time.setHours(self.service_time.getHours() + 8);
            self.service_time = self.service_time.getFullYear().toString()
                + "-" + self.format_do_time(self.service_time.getMonth() + 1)
                + "-" + self.format_do_time(self.service_time.getDate())
                + " " + self.format_do_time(self.service_time.getHours())
                + ":" + self.format_do_time(self.service_time.getMinutes())
                + ":" + self.format_do_time(self.service_time.getSeconds())
        },
        format_do_time: function (i) {
            return i > 9 ? i.toString() : '0' + i.toString();
        }
    });

    var SaveOrderListWidget = Widget.extend({
        template:"tyibs_er_save_order_list_template",
        init:function(parent){
            this._super(parent);
            this.records = [];
        },
        start:function(){
            var self = this;
            self.get_save_order_list();
            setInterval(function(){
                //只有在显示的时候才去刷新此控件
                if(self.$el.css("display")=="block"){
                    self.get_save_order_list();
                }
            }, 1000 * 20 );
            this.init_scoll_panel();
        },
        init_scoll_panel:function(){
            var container = this.$("div.marque-list");
            container.myScroll({
                speed:40, //数值越大，速度越慢
                rowHeight:80 //li的高度,此值要和实际情况贴合的比较近，否则会出现抖动的情况
            });
        },
        get_save_order_list:function(){
            var self = this;
            //self.$("ul.list-group").empty();
            var domain = [['state', '!=', 'archive']];
            if( self.records!=undefined && self.records.length > 0 ){
                var exists_ids = self.records.map(function(item){ return item.id;});
                domain.push(['id','not in', exists_ids]);
            }
            SaveOrder.query(["lift_maintenance_company_id", "lift_code", "service_time", "response_maintenance_company_id","state","lift_id","car_id"])
                .filter(domain)
                .order_by("-service_time")
                .all()
                .then(function(records){
                    if(records!=undefined && records.length>0) {
                        $(".tyibs_tip_no_save_order").remove();
                        self.records = self.records.concat(records);

                        records.forEach(function (record) {
                            var row_widget = new SaveOrderListRowWidget(self, record);
                            row_widget.appendTo(self.$("ul.list-group"));
                        });
                    }
                });
        }
    });

    var BaiduMapWidget = Widget.extend({
        template:"tyis_er_dynamic_map_template",
        init: function(parent, record) {
            this._super(parent);
            this.record = record;
            this.main_id = record.main_id;
            this.response_main_id = record.response_main_id;
            this.car_id = record.car_id;
            this.main_icon = new BMap.Icon("/lift_base/static/src/img/maintenance_company.png",new BMap.Size(32,32));
            this.response_main_icon = new BMap.Icon("/lift_base/static/src/img/salvager_unit.png",new BMap.Size(32,32));
            this.car_icon = new BMap.Icon("/lift_base/static/src/img/rescue_vehicle.png",new BMap.Size(32,32));
            this.move_car_icon = new BMap.Icon("/lift_base/static/src/img/move_car.png", new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
            this.stop_car_icon = new BMap.Icon('/lift_base/static/src/img/stop_car.png', new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
        },
        start: function () {
            this._super();
            var self = this;
            var map = new BMap.Map(self.$("div.tyibs-lift-dynamic-map")[0]);
            self.map = map;
            self.info_window = new BMap.InfoWindow();

            self.show_baidu_map();
            // var btn_block = new TyibsErDynamicMapTemplateBtnBlock(this);
            // btn_block.on("show_or_hide_menu", self, self.show_or_hide_menu);
            // btn_block.appendTo(self.$el.find(".tyibs-lift-dynamic-map"));
            self.init_show_or_hide_menu_text();

        },

        show_baidu_map:function(){
            // 电梯marker
            var self = this;

            if (self.record.gps_address == ""){
                self.add_warning_marker(self.record.ln, self.record.la);
            }else {
                $.ajax({
                    url: "http://api.map.baidu.com/geocoder/v2/?address=" + self.record.gps_address + "&output=json&ak=XYeVsCzcw7Rz0cCt3ZnZtBD2ohUTlMXX&callback=showLocation",
                    dataType: 'jsonp',
                    data: '',
                    jsonp: 'callback',
                    success: function (gps_result) {
                        self.add_warning_marker(gps_result.result.location.lng, gps_result.result.location.lat);
                    },
                    error: function () {
                        alert("无法获取到位置。")
                    }
                });
            }
            self.add_main_marker();

            self.add_car_marker();
            self.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        },
        add_warning_marker: function (lng, lat) {
            var self = this;
            var lift_point = new BMap.Point(lng, lat);
            self.lift_point = lift_point;
            var icon = new BMap.Icon("/er/static/src/img/warning.gif",new BMap.Size(80,80));
            self.map.centerAndZoom(lift_point, 15);
            var marker = new BMap.Marker(lift_point, {icon: icon});

            marker.setTitle(self.record.use_company_id[1]);

            self.map.addOverlay(marker);
            marker.addEventListener("click", function(e){
                self.info_window.setContent("电梯编号：" + self.format_undefined_data(self.record.code) +
                    "<br/>使用单位：" + self.format_undefined_data(self.record.use_company_id[1]) +
                    "<br/>内部编码：" + self.format_undefined_data(self.record.user_inside_code) +
                    "<br/>电梯地址：" + self.format_undefined_data(self.record.use_address));
                marker.openInfoWindow(self.info_window);
            });
        },
        add_main_marker: function () {
            // 添加维保单位marker
            var self = this;
            if (self.main_id){
                new Model("tyibs.base.maintenance.company").query(["name", "address", "contact", "phone", "mobile", "ln", "la"]).filter([["id", "=", self.main_id]]).limit(1).all().then(function (res) {
                    if (res.length > 0){
                        var main_point = new BMap.Point(res[0].ln, res[0].la);
                        var main_marker = new BMap.Marker(main_point, {icon: self.main_icon})
                        self.main_marker = main_marker;
                        var label = new BMap.Label(res[0].name + "-维保单位", {offset   : new BMap.Size(-80, -25)});
                        label.setStyle({
                            "color": "red",
                            "max-width": "none"
                        });
                        main_marker.setLabel(label);
                        main_marker.addEventListener("click", function () {
                            self.set_main_info_window(main_marker, res[0]);
                        });
                        self.map.addOverlay(main_marker);
                        self.add_response_main_marker();
                    }
                })
            }else {
                console.log("没有维保单位");
                self.add_response_main_marker();
            }

        },
        add_response_main_marker: function () {
            // 添加救援单位marker
            var self = this;
            if (!self.response_main_id){
                console.log("没有救援单位");
                return false;
            }else if(self.main_id == self.response_main_id){
                self.main_marker.setIcon(self.response_main_icon);
                var label = self.main_marker.getLabel();
                label.setContent(label.getContent() + "-救援单位");
                console.log("救援单位即维保单位");
                return false;
            }else {
                new Model("tyibs.base.maintenance.company").query(["name", "address", "contact", "phone", "mobile", "ln", "la"]).filter([["id", "=", self.response_main_id]]).limit(1).all().then(function (res) {
                    if (res.length > 0){
                        var response_main_point = new BMap.Point(res[0].ln, res[0].la);
                        var response_main_marker = new BMap.Marker(response_main_point, {icon: self.response_main_icon})
                        var label = new BMap.Label(res[0].name + "-救援单位", {offset   : new BMap.Size(-80, -25)});
                        label.setStyle({
                            "color": "red",
                            "max-width": "none"
                        });
                        response_main_marker.setLabel(label);
                        response_main_marker.addEventListener("click", function () {
                            self.set_main_info_window(response_main_marker, res[0]);
                        });
                        self.response_main_marker = response_main_marker;
                        self.map.addOverlay(response_main_marker);
                    }
                })
            }
        },
        set_main_info_window: function (marker, company) {
            var info_window_html = '<div class="tyibs-map-info-window">'
                                + '<h4>' + company.name + '</h4>'
                                + '<span>地址：'+ company.address +'</span>'
                                + '<br/><span>联系人：'+ company.contact +'</span><br/><span>手机：' + company.mobile + '</span>'
                                + '<br/><span>固定电话：' + company.phone + '</span><br/></div>';
            var info_window = new BMap.InfoWindow(info_window_html);
            marker.openInfoWindow(info_window);
        },
        add_car_marker: function () {
            // 添加救援车辆
            var self = this;
            if(self.car_id){
                new Model("tyibs.base.maintenance.rescue.vehicle").query().filter([["id", "=", self.car_id]]).limit(1).all().then(function (res) {
                    // var main_marker = new BMap.Marker();
                    if (res.length > 0){
                        self.car_record = res[0];
                        self.device_code = res[0].GPS_code;
                        self.polyline = new BMap.Polyline([], {strokeColor:"red", strokeWeight:8, strokeOpacity:1});
                        self.reset_token();
                        self.convertor = new BMap.Convertor();
                        var driving_route = new BMap.DrivingRoute(self.map, {
                            renderOptions: {},
                            onSearchComplete: function (results) {
                                if (driving_route.getStatus() != BMAP_STATUS_SUCCESS) {
                                    return;
                                }
                                var plan = results.getPlan(0);
                                //获取时间
                                var need_time = plan.getDuration(true);
                                //获取距离
                                var need_space = plan.getDistance(true);
                                $("#time_" + self.device_code).html(need_time);
                                $("#space_" + self.device_code).html(need_space);
                            }
                        });
                        self.driving_route = driving_route;
                        self.dynamic_car_interval = setInterval(function () {
                            self.set_dynamic_position();
                        }, 1000 * 5);

                    }
                })
            }else {
                console.log("没有救援车辆");
            }
        },
        reset_token: function () {
            // 设置gps api的token
            var self = this;
            $.post("/api/auth/login", {'username': "zmd_gps_admin", 'password': 'p@ssw0rd'}, function (res) {
               self.token = res.data.token;
               self.set_dynamic_position();
            });
        },
        set_dynamic_position: function () {
            var self = this;
            if(!self.token){
                self.reset_token();
            }else {
                $.ajax({
                    url: '/api/device/gps/list',
                    type: 'POST',
                    data: {
                        device_code: self.device_code
                    },
                    headers: {
                        'x-access-token': self.token
                    },
                    success: function (gps_data) {
                        if (gps_data.code == 0 && gps_data.data.length > 0) {
                            self.convertor.translate([new BMap.Point(gps_data.data[0].lng, gps_data.data[0].lat)], 1, 5, function (data) {
                                if (data.status === 0) {
                                    self.driving_route.search(data.points[0], self.lift_point);
                                    if (self.car_marker != undefined) {
                                        // marker已存在，更改其position
                                        self.car_marker.setPosition(data.points[0]);
                                        var polyline_path = self.polyline.getPath();
                                        polyline_path.push(data.points[0]);
                                        self.polyline.setPath(polyline_path);
                                        $(".tyibs_car_state").html(gps_data.data[0].state);
                                        $(".tyibs_car_address").html(gps_data.data[0].address);
                                        $(".tyibs_car_speed").html(gps_data.data[0].speed);
        //                                    map.panTo(car_marker.getPosition());
                                    } else {
                                        // marker不存在，创建marker
                                        var car_marker = new BMap.Marker(data.points[0]);
                                        self.car_marker = car_marker;
                                        self.map.addOverlay(car_marker);
                                        car_marker.addEventListener('click', function (e) {
                                            self.set_car_info_window(car_marker,gps_data.data[0].state, gps_data.data[0].address, gps_data.data[0].speed);
                                        });
                                        var p = [];
                                        var length = 10 ? gps_data.data.length > 10 : gps_data.data.length;
                                        for (var i = 0; i < length; i++){
                                            p.push(new BMap.Point(gps_data.data[i].lng, gps_data.data[i].lat));
                                        }
                                        self.convertor.translate(p, 1, 5, function (res_data) {
                                            res_data.points.reverse();
                                            self.polyline.setPath(res_data.points);
                                        });

                                        self.map.addOverlay(self.polyline);
                                        self.map.panTo(car_marker.getPosition());

                                    }
                                    // 修改小车车的icon
                                    if (gps_data.data[0].speed > 0){
                                        //车子在动
                                        self.car_marker.setIcon(self.move_car_icon);
                                    }else {
                                        //车子静止
                                        self.car_marker.setIcon(self.stop_car_icon);
                                    }
                                    //改变小车车方向
                                    self.car_marker.setRotation(gps_data.data[0].direction);
                                }
                            });
                        }
                    }
                });
            }
        },
        set_car_info_window: function (marker, state, current_address,speed) {
            var self = this;
            var info_window_html = '<div class="tyibs-map-info-window">'
                + '<h4>' + self.car_record.enterprise_id[1] + '</h4><span>车牌号码：' + self.car_record.code + '</span>'
                + '<br/><span>GPS编码：' + self.car_record.GPS_code + '</span>'
                + '<br/><span>车载电话：' + self.car_record.GPS_mobile + '</span>'
                + '<br/><span>车辆负责人：' + self.car_record.manager + '</span>'
                + '<br/><span>负责人电话：' + self.car_record.manager_mobile + '</span>'
                + '<br/>当前位置：<span class="tyibs_car_address">' + current_address + '</span>'
                + '<br/>车辆状态：<span class="tyibs_car_state">'+ state +'</span>'
                + '<br/>当前车速：<span clsss="tyibs_car_speed">' + speed + '</span>km/h'
                + '<br/><span>距离事故电梯：<span id="space_' + self.car_record.GPS_code + '">获取中...</span></span>'
                + '<br/><span>所需时间：<span id="time_' + self.car_record.GPS_code + '">获取中...</span></span></div>';
            var infoWindow = new BMap.InfoWindow(info_window_html);
            infoWindow.addEventListener('open', function () {
                self.map.panTo(marker.getPosition());
                console.log(marker.getPosition(), self.lift_point);
                self.driving_route.search(marker.getPosition(), self.lift_point);
            });
            marker.openInfoWindow(infoWindow);
        },
        init_show_or_hide_menu_text: function () {
            var self = this;
            if($(".o_sub_menu").css("display") == "none" && $("#oe_main_menu_navbar").css("display") == "none"){
                self.$(".show_or_hide_menu").html("显示菜单");
            }else {
                self.$(".show_or_hide_menu").html("隐藏菜单");
            }
        },
        show_or_hide_menu: function () {
            $(".o_sub_menu").toggle();
            $("#oe_main_menu_navbar").toggle();
            this.init_show_or_hide_menu_text();
        },
        add_marker: function (object, marker_type) {
            //添加marker
            var self = this;
            var point = new BMap.Point(object.ln, object.la);
            var marker = new BMap.Marker(point, {icon: self.set_marker_icon(marker_type)});
            marker.setTitle(object.name);
            self.map.addOverlay(marker);
            // marker.addEventListener("click", function(e){
            //
            // });
            self.set_markers_list(marker, marker_type);
        },
        set_marker_icon: function (marker_type) {
            switch (marker_type){
                case "maintenance":
                    return new BMap.Icon("/lift_base/static/src/img/maintenance_company.png",new BMap.Size(32,32));
                case "level_two_salvager":
                    return new BMap.Icon("/lift_base/static/src/img/salvager_unit.png",new BMap.Size(32,32));
                case "rescue_vehicle":
                    return new BMap.Icon("/lift_base/static/src/img/rescue_vehicle.png",new BMap.Size(32,32));
                default:
                    return new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                        offset: new BMap.Size(10, 25), // 指定定位位置
                        imageOffset: new BMap.Size(0, 0 - 12 * 25) // 设置图片偏移
                    })
            }
        },
        format_undefined_data: function (data) {
           return data == undefined || data == false || data == "false" ? "未知" : data;
        },
        destroy: function () {
            window.clearInterval(this.dynamic_car_interval);
            this._super();
        }
    });

    var DynamicIndexWidget = Widget.extend({
        template:"tyibs_er_dynamic_template",
        events:{
            'click a.tyibs-er-dynamic-show-order': "show_order_detail",
        },
        start:function(){
            var save_order_list_widget = new SaveOrderListWidget(this);

            save_order_list_widget.appendTo(this.$("div.tyibs-er-save-order-list"));
            this.init_baidu_map();
        },
        init_baidu_map: function () {
            //初始化加载一个最新的事故电梯地图
            var self = this;
            SaveOrder.query(['lift_id', 'state']).filter([['state', '!=', 'archive']]).order_by("-service_time").limit(1).all().then(function (res) {
                if(res.length > 0){
                    $(".tyibs_tip_no_save_order").remove();
                    self.show_init_widget(res[0].lift_id[0]);
                    self.show_time_line(res[0].id, res[0].state);
                    // $("div.tyibs-er-save-order-list .list-group").find(":first-child").addClass("selected");
                }
            });
        },
        show_init_widget:function(lift_id, main_id, response_main_id, car_id){
            var self = this;
            if(self.map_widget){
                // 如果之前有地图，销毁前面的地图
                // todo 其实可以改为地图、电梯、车辆、单位的marker个使用一个不用销毁，现在没时间改
                self.map_widget.destroy();
            }
            var timeline_container = self.$("div.tyibs-er-dynamic-timeline-container");
            timeline_container.empty();

            var map_container = self.$("div.tyibs-er-dynamic-map-container");
            map_container.empty();
            // 查询电梯数据
            LiftModel.query(['ln','la', 'code', 'gps_address', 'use_address', 'use_company_id', 'maintenance_company_id', 'user_inside_code'])
                .filter([['id','=',lift_id]])
                .limit(1)
                .all()
                .then(function(records){
                    if(records!=undefined && records.length>0 ){
                        var map_widget = new BaiduMapWidget(self, {
                            ln:records[0].ln,
                            la:records[0].la,
                            gps_address: records[0].gps_address,
                            use_company_id: records[0].use_company_id,
                            'address': records[0].use_address,
                            maintenance_company_id: records[0].maintenance_company_id,
                            user_inside_code: records[0].user_inside_code,
                            code: records[0].code,
                            main_id: main_id,
                            response_main_id: response_main_id,
                            car_id: car_id
                        });
                        self.map_widget = map_widget;
                        map_widget.appendTo(map_container);
                    }
                });

        },
        show_order_detail:function(e){
            $(".list-group-item").removeClass("selected");
            $(e.currentTarget).parent().parent().parent().addClass("selected");
            var lift_id = $(e.currentTarget).data("id");
            var save_order_state = $(e.currentTarget).data("state");
            var save_order_id = $(e.currentTarget).data("order-id");
            var main_id = $(e.currentTarget).data("main-id");
            var response_main_id = $(e.currentTarget).data("response-main-id");
            var car_id = $(e.currentTarget).data("car-id");
            this.show_init_widget(lift_id, main_id, response_main_id, car_id);
            this.show_time_line(save_order_id, save_order_state);
        },
        show_time_line: function (save_order_id, save_order_state) {
            var self = this;
            self.$el.find(".tyibs-timeline-block").empty();
            var domain = [['res_id','=',save_order_id],['res_model','=','tyibs.er.work.order.save']];
            this.alive(Comment.query([]).filter(domain).all().then(function (records) {
                var timeline = new TimelineWidget(self, records, save_order_state);
                timeline.appendTo(self.$el.find(".tyibs-timeline-block"));
            }));
        }
    });


    var TimelineWidget = Widget.extend({
        template: "tyibs_lift_dynamic_timeline_widget_template",
        init: function (parent, records, save_order_state) {
            this._super(parent);
            this.records = records;
            this.step = work_order_sate_for_timeline[save_order_state];
        },
        start: function () {
            var self =this;
            self.records.forEach(function (item) {
                self.$el.find(".tyibs_timeline_" + item.stage).attr("title", self.split_content(item.content));
            });
            self.$el.find('li').removeClass('active');
            self.$el.find('li:lt(' + self.step + ')').addClass('active');
            $("[data-toggle='tooltip']").tooltip();
        },
        split_content:function(content){
            if(content==null || content==undefined || content==""){
                return "";
            }else{
                return content.split("\n").map(function (line) {
                    return  line;
                }).join("<br/>");
            }
        },
    });

    core.action_registry.add('er.dynamic_index', DynamicIndexWidget)

    return {
    };
});
